package com.totoro.rpc.common.codec;

import com.totoro.rpc.common.util.SerializationUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;

import java.util.List;

/**
 * RPC 解码器
 * Created by Niki on 2018/5/21 18:49
 */
//@RequiredArgsConstructor(staticName = "of")
@AllArgsConstructor(access = AccessLevel.PUBLIC)
public class RPCDecoder extends ByteToMessageDecoder {
    private Class<?> genericClass;


    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        if (byteBuf.readableBytes() < 4) {
            return;
        }
        byteBuf.markReaderIndex();
        int dataLength = internalBuffer().readInt();
        if (internalBuffer().readableBytes() < dataLength) {
            internalBuffer().resetReaderIndex();
            return;
        }

        byte[] data = new byte[dataLength];
        byteBuf.readBytes(data);
        list.add(SerializationUtil.deserialize(data, genericClass));
    }
}
